package com.tyrone.concurrent.concurrentUtils;



import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 *
 * 模拟数据库连接只有十个（Semaphore控制），而并发量有
 * @author Tyrone
 * @date 2021/12/22 21:00
 */
public class SemaphoreTest {
    public static final int THREAD_COUNT = 30 ;

    private static ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT);

    private static Semaphore semaphore = new Semaphore(10);

    public static void main(String[] args) {
        for (int i = 0; i < THREAD_COUNT; i++) {
            threadPool.execute(()->{
                try {
                    /**
                     * 线程竞争 semaphore.acquire（） 获取资源
                     */
                    semaphore.acquire();    // P 操作
                    System.out.println(semaphore.availablePermits()+"    Data Save!");
                    semaphore.release();    // V 操作
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        threadPool.shutdown();
    }
}
